package com.jiafa.wjxt.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jiafa.wjxt.entity.OperateProjectItemRequest;
import com.jiafa.wjxt.vo.OperateProjectItemVO;
import com.jiafa.wjxt.entity.TUserProject;
import com.jiafa.wjxt.entity.TUserProjectItem;
import com.jiafa.wjxt.entity.struct.ItemDefaultValueStruct;
import com.jiafa.wjxt.service.TUserProjectItemService;
import com.jiafa.wjxt.service.TUserProjectResultService;
import com.jiafa.wjxt.service.TUserProjectService;
import com.jiafa.wjxt.util.JsonUtils;
import com.jiafa.wjxt.util.ProjectRedisKeyConstants;
import com.jiafa.wjxt.util.Result;
import com.jiafa.wjxt.util.SortUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jiafa
 * @since 2021-05-27
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/project")
public class TUserProjectController {

    @Autowired
    TUserProjectService projectService;
    @Autowired
    TUserProjectItemService projectItemService;
    @Autowired
    TUserProjectResultService projectResultService;

    private final SortUtils sortUtils;

    @Autowired
    TUserProject tUserProject;

    @GetMapping("/myProject")
    @ApiOperation("查询用户的所有问卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current",value = "当前页"),
            @ApiImplicitParam(name = "size",value = "每页的问卷数量"),
            @ApiImplicitParam(name = "userId",value = "用户的id"),
            @ApiImplicitParam(name = "isDeleted",value="是否删除"),
            @ApiImplicitParam(name = "title",value="标题")}
    )
    public Result myProject(Long current, Long size, Long userId, Boolean isDeleted, String title){
        return projectService.myProjects(current,size,userId,isDeleted,title);
    }

    @GetMapping("/recycleProject")
    @ApiOperation("查询用户删除的问卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户的id"),
            @ApiImplicitParam(name = "isDeleted",value="是否删除")}
            )
    public Result recycleProject(Long userId,Boolean isDeleted){
        return projectService.RecycleProjects(userId,isDeleted);
    }

    @GetMapping("/getByTitle")
    @ApiOperation("通过问卷标题查询")
    @ApiImplicitParam(name = "title",value = "问卷的标题")
    public Result getByTitle(String title){
        return projectService.queryByTitle(title);
    }

    @GetMapping("/getByKey")
    @ApiOperation("通过问卷的key查询")
    @ApiImplicitParam(name = "key",value = "问卷的key")
    public Result getByKey(String key){
        Result result = Result.build();
        result.setCode(200);
        result.setMsg("");
        result.setData(projectService.queryByKey(key));
        return result;
    }

    @PostMapping("/createProject")
    public Result createProject(Long userId) {
        tUserProject.setProjectKey(IdUtil.simpleUUID());
        tUserProject.setTitle("问卷名称");
        tUserProject.setDescribes("<p>为了给您提供更好的服务，希望您能抽出几分钟时间，将您的感受和建议告诉我们，我们非常重视每位 用户的宝贵意见，期待您的参与！现在我们就马上开始吧！</p>");
        tUserProject.setUserId(userId);
        tUserProject.setStats(1);
        projectService.save(tUserProject);
        Result result = Result.build();
        result.setCode(200);
        result.setMsg(null);
        result.setData(tUserProject.getProjectKey());
        return result;
    }

    @PostMapping("/update")
    public Result updateProject(TUserProject project){
        System.out.println(project);
        TUserProject project1 = projectService.queryByKey(project.getProjectKey());
        project1.setTitle(project.getTitle());
        project1.setDescribes(project.getDescribes());
        projectService.updateById(project1);
        Result result = Result.build();
        result.setCode(200);
        result.setMsg("");
        result.setData(project1);
        return result;
    }

    @GetMapping("/item/list")
    public Result queryProjectItem(@RequestParam String key){
        System.out.println(key);
//        List<TUserProjectItem> itemList = projectItemService.queryProjectItem(projectKey);
//        Result result = Result.build();
//        result.setData(itemList);
//        result.setMsg("查询成功");
//        result.setCode(200)；
        return projectService.queryProjectItem(key);
    }

    /**
     * 格式化项目Item的数据
     */
    private TUserProjectItem formatProjectItem(OperateProjectItemRequest request) {
        //把Map转换成Bean 在转换成Map 去除不在bean字段列表的多字段
        Object bean = BeanUtil.mapToBean(request.getExpand(), request.getType().getExpandClass(), true);
        TUserProjectItem entity = new TUserProjectItem();
        BeanUtil.copyProperties(request, entity,"defaultValue");
        entity.setExpand(BeanUtil.beanToMap(bean));
        //默认值格式化 1判断是否是Json
        Object defaultValue = request.getDefaultValue();
        if (ObjectUtil.isNotEmpty(defaultValue)) {
            boolean json = JSONUtil.isJson(JsonUtils.objToJson(request.getDefaultValue()));
            if (json) {
                entity.setDefaultValue(new ItemDefaultValueStruct(true, JsonUtils.objToJson(request.getDefaultValue())));
            }
        }
        entity.setDefaultValue(new ItemDefaultValueStruct(false, defaultValue));
        return entity;
    }

    @PostMapping("/item/update")
    public Result updateProjectItem(@RequestBody OperateProjectItemRequest projectItem){
        System.out.println(projectItem);
        boolean update = projectItemService.update(formatProjectItem(projectItem), Wrappers.<TUserProjectItem>lambdaQuery()
                .eq(TUserProjectItem::getProjectKey, projectItem.getProjectKey())
                .eq(TUserProjectItem::getFormItemId, projectItem.getFormItemId()));
        Result result = Result.build();
        result.setCode(200);
        result.setMsg("");
        result.setData(formatProjectItem(projectItem));
        return result;
    }

    @PostMapping("item/create")
    public Result createProjectItem(@RequestBody OperateProjectItemRequest request){
        TUserProjectItem entity = formatProjectItem(request);
        System.out.println(entity);
        //排序下标计算
        entity.setSort(sortUtils.getInitialSortPosition(
                StrUtil.format(ProjectRedisKeyConstants.PROJECT_ITEM_POS_DELTA, request.getProjectKey())));
        boolean save = projectItemService.save(entity);
        Result result = Result.build();
        result.setMsg("");
        result.setCode(200);
        result.setData(new OperateProjectItemVO(entity.getSort(), entity.getId(), save));
        return result;
    }

    @GetMapping("/item/max-form-id")
    public Result queryProjectMaxFormItemId(String key) {
        TUserProjectItem entity = projectItemService.getOne(Wrappers.<TUserProjectItem>lambdaQuery()
                .eq(TUserProjectItem::getProjectKey, key).select().orderByDesc(TUserProjectItem::getFormItemId).last("limit 1"));
        return Result.ok(ObjectUtil.isNotNull(entity) ? entity.getFormItemId() : null);
    }

    @PostMapping("/item/delete")
    public Result deleteProjectItem(@RequestBody OperateProjectItemRequest request) {
        boolean delete = projectItemService.remove(Wrappers.<TUserProjectItem>lambdaQuery()
                .eq(TUserProjectItem::getProjectKey, request.getProjectKey())
                .eq(TUserProjectItem::getFormItemId, request.getFormItemId())
                .eq(TUserProjectItem::getType, request.getType().getValue() - 1));
        return Result.success(""+delete);
    }

    @GetMapping("/change/stats")
    public Result changStats(String key){
        System.out.println(key);
        return projectService.changeStats(key);
    }

    @GetMapping("/change/toStop")
    public Result toStop(String key){
        System.out.println(key);
        return projectService.toStop(key);
    }

    @GetMapping("/change/toDelete")
    public Result toDelete(String key){
        System.out.println(key);
        return projectService.toDelete(key);
    }

    @GetMapping("/change/recovery")
    public Result recovery(String key){
        System.out.println(key);
        return projectService.recovery(key);
    }
}
